package com.ctrlspace.model;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import org.json.simple.JSONAware;
import org.json.simple.JSONObject;

public enum FileType implements JSONAware {
	// Source types
	ENUM("enum", ".java"), CLASS("java", ".java"), INTERFACE("interface", ".java"),
	PACKAGE("package"), EMPTY_PACKAGE("emptyPackage"),
	// Web types
	HTML("html", ".html"), XML("xml", ".xml"), JSP("jsp", ".jsp"), CSS("cssIcon", ".css"), JS("jsIcon", ".js"), JSON("json", ".json"),
	// Other types
	FILE("file"), FOLDER("folder"), UNKNOWN("unknown");
	
	static HashMap<String, FileType> types = new HashMap<String, FileType>();
	static {
		for (FileType f : FileType.values()) {
			types.put(f.getIconName(), f);
		}
	}

	private String iconName;
	private String extension;

	private FileType(String iconName) {
		this.iconName = iconName;
		this.extension = "";
	}

	private FileType(String iconName, String extension) {
		this.iconName = iconName;
		this.extension = extension;
	}

	public String getIconName() {
		return iconName;
	}

	public void setIconName(String iconName) {
		this.iconName = iconName;
	}

	public String getExtension() {
		return extension;
	}

	public void setExtension(String extension) {
		this.extension = extension;
	}
	
	public static FileType find(String typeName) {
		return types.get(typeName);
	}
	
	public static FileType findExtension(String extension) {
		return findExtension(extension, false);
	}
	
	public static FileType findExtension(String extension, boolean isFolder) {
		if (isFolder) {
			return FileType.FOLDER;
		}
		
		if (extension.equals("")) {
			return FileType.FILE;
		}

		Iterator<String> it = types.keySet().iterator();
		while (it.hasNext()) {
			String key = it.next();
			FileType targetType = types.get(key);
			String ext = targetType.getExtension();
			if (ext.equals(extension)) {
				return targetType;
			}
		}
		
		return FileType.UNKNOWN;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public String toJSONString() {
		Map obj = new LinkedHashMap();
		obj.put("extension", extension);
		obj.put("type", iconName);
		return JSONObject.toJSONString(obj);
	}
}
